package com.showsu.editor.asyncService.impl;

import com.alibaba.fastjson2.JSON;
import com.showsu.editor.asyncService.ICheckAwemeIncludedAsyncService;
import com.showsu.editor.entity.bo.XhsAwemeBusinessV2;
import com.showsu.editor.entity.bo.XhsAwemeListBusiness;
import com.showsu.editor.entity.dto.XhsAwemeLimitedDTO;
import com.showsu.editor.entity.platform.xhs.AwemeDetailPlatformDataResult;
import com.showsu.editor.entity.po.TblXhsCheckAwemeIncludedRecord;
import com.showsu.editor.entity.vo.XhsAwemeDetail;
import com.showsu.editor.enums.UserExpPackageTypeEnum;
import com.showsu.editor.enums.UserPrivilegeEnum;
import com.showsu.editor.enums.XhsAwemeIsIncludedEnum;
import com.showsu.editor.enums.XhsAwemeIsLimitedEnum;
import com.showsu.editor.manage.XhsBusinessManager;
import com.showsu.editor.service.IUserExppackageService;
import com.showsu.editor.service.IXhsCheckAwemeIncludedRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @Author: jph
 * @Description:
 * @Date: Created in 15:51 下午 2024/3/1
 * @Modified By:
 */
@Service
@Slf4j
public class CheckAwemeIncludedAsyncServiceImpl implements ICheckAwemeIncludedAsyncService {

    @Autowired
    @Lazy
    private XhsBusinessManager xhsBusinessManager;

    @Autowired
    private IXhsCheckAwemeIncludedRecordService xhsCheckAwemeIncludedRecordService;

    @Autowired
    private IUserExppackageService userExppackageService;

    @Override
    @Async("checkAwemeIncludedExecutor")
    public void executeAsyncCheckAwemeIncludedTask(Long traceId, XhsAwemeDetail awemeInfo, Long userId, String keyword, UserExpPackageTypeEnum businessType) {
        XhsAwemeListBusiness xhsAwemeListBusiness = null;
        XhsAwemeIsLimitedEnum xhsAwemeIsLimitedEnum = XhsAwemeIsLimitedEnum.Fail;
        AwemeDetailPlatformDataResult.User user = awemeInfo.getUser();
        //查笔记限流
        XhsAwemeLimitedDTO getXhsAwemeLimitedDTO = xhsBusinessManager.getXhsAwemeLimited(user.getUserid(), awemeInfo.getAwemeId());
        if (getXhsAwemeLimitedDTO != null) {
            xhsAwemeListBusiness = getXhsAwemeLimitedDTO.getXhsAwemeList();
            xhsAwemeIsLimitedEnum = XhsAwemeIsLimitedEnum.getByCode(getXhsAwemeLimitedDTO.getXhsAwemeIsLimited());
        }
        if (xhsAwemeListBusiness == null) {
            xhsAwemeListBusiness = new XhsAwemeListBusiness();
            xhsAwemeListBusiness.setSuccess(false);
        }
        TblXhsCheckAwemeIncludedRecord updateRecord = new TblXhsCheckAwemeIncludedRecord();
        updateRecord.setId(traceId);
        updateRecord.setUserAwemeList(JSON.toJSONString(xhsAwemeListBusiness));
        updateRecord.setIsLimited(xhsAwemeIsLimitedEnum.getCode());
        xhsCheckAwemeIncludedRecordService.updateById(updateRecord);
        //查笔记收录/排名
        XhsAwemeBusinessV2 xhsAwemeBusiness = xhsBusinessManager.getAwemeIncludedSearchResult(awemeInfo, keyword);
        //任务失败
        if (xhsAwemeBusiness == null) {
            //笔记排名任务失败，返还冻结的次数
            if (businessType != null && businessType.equals(UserExpPackageTypeEnum.XHS_AWEME_RANK_QUERY)) {
                Boolean reduceFreezeTimes = userExppackageService.returnFreezeTimes(userId, businessType, 1);
                if (! reduceFreezeTimes) {
                    log.info("executeAsyncCheckAwemeIncludedTask()，笔记排名任务失败后处理扣减冻结次数失败，userId:{},keyword:{},traceId:{}", userId, keyword, traceId);
                }
            }
            //笔记收录任务失败，返还次数
            if (businessType != null && businessType.equals(UserExpPackageTypeEnum.XHS_AWEME_INCLUDE_QUERY)) {
                Boolean returnTimes = xhsBusinessManager.reduceTime(userId, UserPrivilegeEnum.XHS_AWEME_INCLUDED, -1);
                if (! returnTimes) {
                    log.info("executeAsyncCheckAwemeIncludedTask()，笔记收录任务失败后返还次数失败，userId:{},traceId:{}", userId, traceId);
                }

            }
            updateRecord.setIsIncluded(XhsAwemeIsIncludedEnum.Fail.getCode());
            xhsCheckAwemeIncludedRecordService.updateById(updateRecord);
        }
        //任务成功
        else {
            //笔记排名，扣减冻结的次数
            if (businessType != null && businessType.equals(UserExpPackageTypeEnum.XHS_AWEME_RANK_QUERY)) {
                Boolean reduceFreezeTimes = userExppackageService.reduceFreezeTimes(userId, businessType, 1);
                if (! reduceFreezeTimes) {
                    log.info("executeAsyncCheckAwemeIncludedTask()，笔记排名任务扣减冻结次数失败，userId:{},keyword:{},traceId:{}", userId, keyword, traceId);
                }
            }
            if (xhsAwemeBusiness.getSearchCriteria() != null) {
                updateRecord.setSearchCriteria(JSON.toJSONString(xhsAwemeBusiness.getSearchCriteria()));
            }
            updateRecord.setRanking(xhsAwemeBusiness.getRanking());
            updateRecord.setAwemeCount(xhsAwemeBusiness.getAwemeCount());
            updateRecord.setFinishTime(new Date());
            updateRecord.setIsIncluded(xhsAwemeBusiness.getIncluded().getCode());
            xhsCheckAwemeIncludedRecordService.updateById(updateRecord);
        }
    }
}
